import React, { useState } from 'react';
import { useGame } from '../GameContext';
import { motion } from 'framer-motion';

const Oven: React.FC = () => {
  const { state, takePizzaFromOven, deliverPizza } = useGame();
  const { ovenSlots, orders } = state;
  const [draggedPizza, setDraggedPizza] = useState<string | null>(null);
  const [dragTarget, setDragTarget] = useState<string | null>(null);

  // 从烤炉取出披萨
  const handleTakePizza = (slotId: number) => {
    const pizzaType = takePizzaFromOven(slotId);
    if (pizzaType) {
      // 可以在这里添加拖拽逻辑，或者直接触发交付
      setDraggedPizza(pizzaType);
    }
  };

  // 处理拖拽开始
  const handleDragStart = (e: React.DragEvent, slotId: number) => {
    const slot = ovenSlots.find(s => s.id === slotId);
    if (slot && (slot.status === 'ready' || slot.status === 'burnt') && slot.pizza) {
      e.dataTransfer.setData('pizzaType', slot.pizza);
      e.dataTransfer.setData('slotId', slotId.toString());
    }
  };

  // 处理拖拽结束
  const handleDragEnd = () => {
    setDragTarget(null);
  };

  // 处理拖入
  const handleDragOver = (e: React.DragEvent) => {
    e.preventDefault();
  };

  // 处理拖放
  const handleDrop = (e: React.DragEvent, orderId: string) => {
    e.preventDefault();
    const pizzaType = e.dataTransfer.getData('pizzaType');
    const slotId = parseInt(e.dataTransfer.getData('slotId'));
    
    if (pizzaType && !isNaN(slotId)) {
      const success = deliverPizza(orderId, pizzaType as any);
      if (success) {
        // 交付成功，取出披萨
        takePizzaFromOven(slotId);
      }
    }
    
    setDragTarget(null);
  };

  // 获取烤炉槽位的显示信息
  const getSlotInfo = (slot: any) => {
    switch (slot.status) {
      case 'empty':
        return { text: '空', icon: '🧺', color: 'text-gray-500' };
      case 'baking':
        const progress = slot.remainingTime ? Math.max(0, (slot.remainingTime / (slot.pizza ? 20 : 15)) * 100) : 0;
        return {
          text: `烘烤中: ${Math.ceil(slot.remainingTime || 0)}秒`, 
          icon: '🍕', 
          color: 'text-amber-700',
          progress: 100 - progress
        };
      case 'ready':
        return { text: '已完成！', icon: '✅', color: 'text-green-600' };
      case 'burnt':
        return { text: '烤焦了！', icon: '❌', color: 'text-red-600' };
      default:
        return { text: '未知', icon: '❓', color: 'text-gray-500' };
    }
  };

  return (
    <div className="game-card">
      <h2 className="text-2xl font-bold text-amber-800 mb-4">烤炉</h2>
      <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
        {ovenSlots.map((slot) => {
          const slotInfo = getSlotInfo(slot);
          const isReadyOrBurnt = slot.status === 'ready' || slot.status === 'burnt';
          
          return (
            <motion.div
              key={slot.id}
              className={`oven-slot ${slot.status}`}
              whileHover={{ scale: isReadyOrBurnt ? 1.05 : 1 }}
              whileTap={{ scale: isReadyOrBurnt ? 0.95 : 1 }}
              onClick={() => isReadyOrBurnt && handleTakePizza(slot.id)}
              draggable={isReadyOrBurnt}
              onDragStart={(e) => handleDragStart(e, slot.id)}
              onDragEnd={handleDragEnd}
            >
              <span className="text-4xl mb-2">{slotInfo.icon}</span>
              <p className={`font-bold ${slotInfo.color}`}>{slotInfo.text}</p>
              
              {slot.pizza && (
                <p className="text-sm mt-1">{slot.pizza}</p>
              )}
              
              {slot.status === 'baking' && slotInfo.progress !== undefined && (
                <div className="progress-bar">
                  <motion.div 
                    className="progress-bar-fill"
                    initial={{ width: '0%' }}
                    animate={{ width: `${slotInfo.progress}%` }}
                    transition={{ duration: 0.1, ease: "linear" }}
                  />
                </div>
              )}
              
              {isReadyOrBurnt && (
                <motion.div 
                  className="absolute top-2 right-2 text-xs bg-white/80 px-2 py-1 rounded-full"
                  animate={{ scale: [1, 1.2, 1] }}
                  transition={{ repeat: Infinity, duration: 2 }}
                >
                  点击取出
                </motion.div>
              )}
            </motion.div>
          );
        })}
      </div>
      
      {/* 拖拽提示 */}
      {draggedPizza && (
        <motion.div 
          className="mt-4 p-3 bg-blue-100 rounded-lg text-center"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.3 }}
        >
          <p>将 {draggedPizza} 披萨拖放到订单上完成交付！</p>
          <button 
            className="mt-2 px-4 py-1 bg-blue-500 text-white rounded"
            onClick={() => setDraggedPizza(null)}
          >
            取消
          </button>
        </motion.div>
      )}
    </div>
  );
};

export default Oven;